<template>
  <div>
    <form-content
      :rules="rules"
      :form-items="formItems"
      :beforeSubmit="beforeSubmit"
      :handleInitFormData="handleInitFormData"
      :submitApi="submitApi"
      :formStateInit="detail"
      :preview="preview"
      :afterSubmit="afterSubmit"
      @formChange="formChange"
    >
      <template #mode="{ item, formState}">
        <a-card size="small">
          <template #title>
            <a-form-item style="margin-bottom: 0" label="模版选择">
              <a-radio-group :disabled="preview" v-model:value="formState['mode']" @change="v => onModeChange(v,formState)"
              :options="[
                {label: '一行一个', value: 'one_line_one'},
                {label: '一行多个', value: 'one_line_more'}
              ]">
              </a-radio-group>
            </a-form-item>
          </template>
          <template #extra v-if="!preview">
            <a-button type="primary" v-if="formState.mode == 'one_line_more'" @click="onAdd(formState.list)">新增模块</a-button>
          </template>
            <div v-for="(v,i) in formState.list" :key="v.key" class="box-list">
              <a-button danger ghost class="list-del-btn" v-if="formState.list.length > 1" @click="listDel(i, formState.list)">删除</a-button>
              <a-form-item label="图片" :labelCol="{span:3}" :wrapper-col="{ span: 14, }" 
                :name="['list', i, 'pic']"
                :rules="{
                  type: 'array',
                  required: true,
                  message: '请选择',
                }">
                <Uploader :mutiple="false" :disabled="preview" :maxLen="1" v-model:value="formState.list[i].pic" />
              </a-form-item>
              <a-form-item label="跳转类型" 
                :labelCol="{span:3}" 
                :wrapper-col="{ span: 8, }" 
                :name="['list', i, 'jump_type']"
                :rules="{
                  required: true,
                  message: '请选择',
                }">
                <a-select placeholder="请选择" v-model:value="formState.list[i].jump_type" :disabled="preview"
                  :options="[
                    {label:'不跳转',value:'off'},
                    {label:'自定义',value:'custom'},
                  ]" />
              </a-form-item>
              <a-form-item label="跳转地址" v-if="formState.list[i].jump_type == 'custom'" :labelCol="{span:3}" :wrapper-col="{ span: 14, }" 
                :name="['list', i, 'url']"
                :rules="{
                  required: true,
                  message: '请输入',
                }">
                <a-input placeholder="请输入" :disabled="preview" v-model:value="formState.list[i].url"/>
              </a-form-item>
            </div>
        </a-card>
      </template>
    </form-content>
  </div>
</template>

<script>
import { ref, toRefs, toRef, reactive, onMounted } from 'vue';
import {useRouter} from 'vue-router';
import { message } from 'ant-design-vue';
import { formItems, formItems2Rules } from './config';
import { add, info, update } from '../api';

const listItem = () => ({
  pic: [],
  jump_type: undefined,
  url: '',
  key: Date.now()
})
export default {
  data() {
    return {
      formItems
    };
  },
  setup(props, context) {
    const router = useRouter();
    const {query, name: routeName} = router.currentRoute.value;
    const rules = ref(formItems2Rules);
    const state = reactive({
      preview: routeName.includes('detail'),
      detail: {}
    })
    const afterSubmit = (res) => {
      res.code == 0 && message.success('提交成功');
      router.push({name: 'pluginList'});
    };
    const beforeSubmit = (data) => {
      const custom = {
        mode: data.mode,
        list: data.list.map(item => {
          return {
            ...item,
            pic: item.pic[0]
          }
        })
      }
      data.custom = JSON.stringify(custom)
      return data;
    };
    const handleInitFormData = (data) => {
      data.mode = 'one_line_one';
      data.list = [listItem()];
      return data;
    }
    const onAdd = (list) => {
      list.push(listItem())
    }
    const listDel = (index, list) => {
      list.splice(index, 1)
    }
    const onModeChange = (v, data) => {
      const val = v.target ? v.target.value : v;
      const list = data.list;
      if (val === 'one_line_one') {
        data.list = list.slice(0,1);
      }
    }
    const formChange = (current, formState, source, item ) => {
      if (current.name === 'category_id') {
        const [v, vdata] = item;
        if (v) {
          formState.company_id = vdata.company_id;
        }
      }
    }
    onMounted(() => {
      if (query.id) {
        info({id: Number(query.id)}).then(res => {
          const {data} = res;
          const {custom} = data;
          if (custom) {
            const {mode, list = []} = JSON.parse(custom);
            data.mode = mode;
            data.list = list.map(item => {
              return {
                ...item,
                pic: [item.pic]
              }
            });
          }
          state.detail = data;
        })
      }
    })

    const submitApi = (p) => {
      p.type = 'image';
      p.id = query.id ? Number(query.id) : query.id;
      return query.id ? update(p) : add(p);
    }

    return {
      ...toRefs(state),
      submitApi,
      formChange,
      onModeChange,
      listDel,
      onAdd,
      handleInitFormData,
      beforeSubmit,
      afterSubmit,
      rules,
    };
  },
};
</script>

<style scoped>
.box-list{
  position: relative;
  border:1px solid #eee;
  padding-top:10px;
  margin-top: 10px;
}
.list-del-btn{
  position:absolute;
  right: 10px
}
</style>